// Modules to control application life and create native browser window
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')
const net = require('net')
const port = 7001
const ip = require('ip')
const env = require('node-env-file');

env(app.getAppPath() + '/src/.env.' + (process.env.NODE_ENV ? process.env.NODE_ENV : 'dev'))

if (!process.env.APP_SEVER_ADDRES) {
  return false
}

let mainContentAddress = process.env.APP_SEVER_ADDRES

// 检测端口是否被占用
function portIsOccupied (port, onSuccess, onError) {
  // 创建服务并监听该端口
  var server = net.createServer().listen(port)

  server.on('listening', function () { // 执行这块代码说明端口未被占用
    server.close() // 关闭服务
    console.log('The port[' + port + '] is available.') // 控制台输出信息

    onSuccess()
  })

  server.on('error', function (err) {
    if (err.code === 'EADDRINUSE') { // 端口已经被使用
      console.log('The port[' + port + '] is occupied, please change other port.')

      onError()
    }
  })
}


ipcMain.on('newModal',(e,arg)=> {
  console.log('receive command')

  portIsOccupied(port, function () {
    const startServer = require('./server/index')
    startServer()
  }, function () {

  })

  mainWindow.webContents.send('receive', mainContentAddress)

})


let mainWindow
let cihldWindow

function buildChildWindow() {
 if (!cihldWindow) {
  cihldWindow = new BrowserWindow({
    width: 1250,
    height: 1000,
    autoHideMenuBar: true,
    show: false,
    webPreferences: {
      webgl: false,
      webSecurity: false,
      webviewTag: true,
      nodeIntegration: true,
      experimentalFeatures: true,
      preload: path.join(__dirname, 'preload.js')
    }
  })

  cihldWindow.on('closed', function() {
    cihldWindow = null
  })
 }

}



function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1900,
    height: 1000,
    autoHideMenuBar: true,
    webPreferences: {
      webgl: false,
      webSecurity: false,
      webviewTag: true,
      nodeIntegration: true,
      experimentalFeatures: true,
      preload: path.join(__dirname, 'preload.js')
    }
  })

   buildChildWindow()


  // and load the index.html of the app.
  // mainWindow.loadFile('front/dist/index.html')
  if (process.env.NODE_ENV === 'dev') {
    mainWindow.loadURL(mainContentAddress)
    // Open the DevTools.
    // mainWindow.webContents.openDevTools()
  } else {
    // mainWindow.loadFile('front/dist/index.html')
    mainWindow.loadURL(mainContentAddress)
  }


  mainWindow.on('closed', function() {
    if (cihldWindow && cihldWindow.closable) {
      cihldWindow.close()
    }
  })

  mainWindow.webContents.on('did-finish-load',function(){
    if (cihldWindow) {
      cihldWindow.loadURL(mainContentAddress + '/tmp')
      // cihldWindow.show()
      cihldWindow.webContents.openDevTools({
        mode: 'right'
      })
      // console.log(cihldWindow.webContents)
    }
  });

}

ipcMain.on('openchildurl', (e, arg) => {
  if (cihldWindow) {
    cihldWindow.loadURL(mainContentAddress + '/tmp')
  }
})

ipcMain.on('reloadchildurl', (e, arg) => {
  console.log('reloadchildurl')
  if (cihldWindow) {
    cihldWindow.reload()
  } else {
    buildChildWindow()
    cihldWindow.loadURL(mainContentAddress + '/tmp')
    cihldWindow.webContents.openDevTools({
      mode: 'right'
    })
  }
  if (!cihldWindow.isVisible()) {
    cihldWindow.show()
  }
})


// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow)

app.on('ready', () => {
  // if (process.env.NODE_ENV !== 'production') {
  //   require('vue-devtools').install()
  // }
})

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
